<?php

namespace App\Admin\Forms;

use App\Admin\Renderable\UserTable;
use Dcat\Admin\Widgets\Form;
use App\Models\User;
use App\Models\Coupon;
class CouponAdd extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $coupons_config_id = $input['coupons_config_id'];
//            Request::input("coupons_config_id");
        $user_id = $input['user_id'];
//            Request::input("user_id");
        $where['user_id'] = $user_id;
        $where['coupons_config_id'] = $coupons_config_id;
        if (Coupon::where($where)->count()>0){
            return $this->response()->error("该用户已发放过该礼品券");
        }
        if (!$coupons_config_id){
           return $this->response()->error('发放的礼品券必须');
        }else{
            if (!$user_id){
              return  $this->response()->error('发放的用户必须');
            }
            Coupon::addCoupon($user_id,$coupons_config_id);
        }
        // dump($input);

        // return $this->response()->error('Your error message.');

        return $this
				->response()
				->success('添加成功')
				->redirect("coupons");
    }

    /**
     * Build a form here.
     */
    public function form()
    {
//        dd($this->data->coupons_config_id);
            $coupons_config_id = $this->data()->coupons_config_id;
//            dd($coupons_config_id);
            $this->confirm('确定要给该用户发送此券么？', '提示');
            $this->hidden("coupons_config_id")->value($coupons_config_id);
            $this->selectTable("user_id")
                ->title("用户选择")
                ->from(UserTable::make())
                ->model(User::class,'id',"nickname");
    }

    /**
     * The data of the form.
     *
     * @return array
     */
//    public function default()
//    {
//        return [
//            'name'  => 'John Doe',
//            'email' => 'John.Doe@gmail.com',
//        ];
//    }
}
